package com.example.scheduledtask.schedule;

import com.example.scheduledtask.generator.domain.Cron;
import com.example.scheduledtask.generator.domain.TbProduct;
import com.example.scheduledtask.generator.service.CronService;
import com.example.scheduledtask.generator.service.TbProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName DynamicTask
 * @Description
 * @Author huyingliang
 * @Date 2024-02-04 15:10
 */
@Component
/*动态的定时任务 就是说我们把定时任务的循环时间写在数据库中 可以随时的更改而不需要重启应用
* 当然，前提是 数据库中的 cron表达式是正确的 如果错误一次，那么就需要重新启动应用才行*/
public class DynamicTask implements SchedulingConfigurer {

    @Autowired
    private CronService cronService;

    @Autowired
    private TbProductService tbProductService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                /*任务的具体内容*/
                TbProduct byId = tbProductService.getById(2);
                System.out.println(byId);
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                /*获取执行周期的具体代码*/
                Cron cron = cronService.getById(1);
                String stringCron = cron.getCron();
                return new CronTrigger(stringCron).nextExecutionTime(triggerContext);
            }
        });
    }
}
